﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using EncryptionLib.Signature;
using EncryptionLib.Users;
using System.IO;
using System.Diagnostics;

namespace ExcelDiSign
{
    public partial class frmSign : Form
    {
        public string DocumentPath
        {
            get;
            set;
        }
        
        public IUserManager UserManager
        {
            get;
            set;
        }

        public frmSign()
        {
            InitializeComponent();
        }

        private void frmSign_Load(object sender, EventArgs e)
        {
            txtDoc.Text = DocumentPath;
            txtSignatureFile.Text = DocumentPath + ".sig";
            SendMessage(new HandleRef(txtEmail, txtEmail.Handle),
                0x1501, IntPtr.Zero, "example@abc.com");
        }

        private void chkPassphrase_CheckedChanged(object sender, EventArgs e)
        {
            txtPassphrase.UseSystemPasswordChar = !chkPassphrase.Checked;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnSignatureFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.AddExtension = dlg.AutoUpgradeEnabled
                = dlg.OverwritePrompt = dlg.RestoreDirectory = true;
            dlg.Title = "Choose a place to save signature file";
            dlg.DefaultExt = "sig";
            dlg.Filter = "Signature file (*.sig)|*.sig|All files(*.*)|*.*||";
            dlg.FilterIndex = 0;

            if (dlg.ShowDialog(this) == DialogResult.OK)
            {
                txtSignatureFile.Text = dlg.FileName;
            }
        }

        private void llblHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            MessageBox.Show(this, "Finally, you clicked me...\r\nI'm sorry because it's hard for you to use this add-in,\r\n so find the way to use it by yourself!",
                "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void btnSign_Click(object sender, EventArgs e)
        {
            string sDocFile = txtDoc.Text.Trim();
            string sSignFile = txtSignatureFile.Text.Trim();
            if(string.IsNullOrEmpty(sSignFile))
            {
                MessageBox.Show(this, "Please set a valid signature file.",
                    "Err...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtSignatureFile.Focus();
                return;
            }

            string sEmail = txtEmail.Text.Trim();
            string sPassphrase = txtPassphrase.Text.Trim();
            if(string.IsNullOrEmpty(sEmail) || string.IsNullOrEmpty(sPassphrase))
            {
                MessageBox.Show(this, "Please enter a valid email/passphrase.",
                    "Err...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail.Focus();
                return;
            }

            UserData userData = UserManager.LoginByEmail(sEmail, sPassphrase);
            if(userData == null)
            {
                MessageBox.Show(this, "Invalid email/passphrase.\r\nTry again, please.",
                    "Login failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail.Focus();
                return;
            }

            try
            {
                string sCpFile = Path.GetTempFileName();
                File.Copy(sDocFile, sCpFile, true);
                Signer.Sign(userData, sPassphrase, sCpFile/*sDocFile*/, sSignFile);
                try
                {
                    File.Delete(sCpFile);
                }
                catch (System.Exception /*ex*/)
                {
                    Debug.WriteLine("Error when deleting temp file.");
                }
                MessageBox.Show(this, "Done!", "Successfully",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                Close();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(this,
                    string.Format("An unexpected error has occurred when signing.\r\n\r\nError: {0}", ex.Message),
                    "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtEmail.Focus();
            }
            
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        private static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, String lParam);
    }
}
